package elsa.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import elsa.bean.ScsUser;
import elsa.tools.Mess;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Controller
public class LoginController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @CrossOrigin
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            System.out.println(createText);
            httpServletRequest.getSession().setAttribute("vrifycode", createText);
            System.out.println("sessionId:"+httpServletRequest.getSession().getId());
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @CrossOrigin
    @RequestMapping("/loginUser")
    @ResponseBody
    public Mess loginUser(String username, String password, String vrifycode,HttpServletRequest httpServletRequest) {
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifycode");
        System.out.println("sessionId:"+httpServletRequest.getSession().getId());
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        if(captchaId!=null&&captchaId.equals(vrifycode)) {
            try {
                subject.login(usernamePasswordToken);   //完成登录;
                SecurityUtils.getSubject().getSession().setTimeout(-1000);
                ScsUser scsUser = (ScsUser) subject.getPrincipal();
                if (scsUser.getState().equals("禁用")) {
                    return Mess.info(0, "用户已被禁用!", "");
                } else {
                    return Mess.info(0, "登录成功", subject.getSession().getId().toString());
                }
            } catch (Exception e) {
                return Mess.info(0, "用户名密码错误!", "");//返回登录页面
            }
        }else {
            return Mess.info(0,"验证码错误","");
        }
    }

    @CrossOrigin
    @RequestMapping("/loginUserNo")
    @ResponseBody
    public Mess loginUser(String username, String password) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录;
            SecurityUtils.getSubject().getSession().setTimeout(-1000);
            ScsUser scsUser = (ScsUser) subject.getPrincipal();
            if (scsUser.getState().equals("禁用")) {
                return Mess.info(0, "用户已被禁用!", "");
            } else {
                return Mess.info(0, "登录成功", subject.getSession().getId().toString());
            }
        } catch (Exception e) {
            return Mess.info(0, "用户名密码错误!", "");//返回登录页面
        }
    }

    @CrossOrigin
    @RequestMapping(value = "/logout",method=RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("public")
    public void logOut() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }else {
        }
    }
}
